<?php
namespace Shop\Controller;

use Common\Controller\AdminbaseController;
use Think\Db;
use Think\Page;

class ShopController extends AdminbaseController
{

    protected $data_model;
    protected $floor_model;
    protected $format_model;
    function _initialize()
    {
        parent::_initialize();
        $this->data_model = D('Shop');
        $this->floor_model = D('Floor');
        $this->format_model = D('Format');
    }

    public function index()
    {
        $count      = $this->data_model->count();// 查询满足要求的总记录数
        $page = $this->page($count,20);
        $show = $page->show('Admin');
        //$data = $this->data_model->order("`floorID` ASC")->select();
        $sql = "select a.*,b.name floorname,d.savename,d.savepath,d.size from ".C('DB_PREFIX')."shop a left join ".C('DB_PREFIX')."floor b on a.floorID = b.id 
            left join ".C('DB_PREFIX')."attachment d on a.attachmentID = d.id order by a.floorID asc limit ".$page->firstRow.",".$page->listRows;
        $data = $this->data_model->query($sql);        
        foreach ($data as &$temp){
            $arr = $this->format_model->where("id in (".$temp['formatid'].")")->Field("name")->select();
            $tem = "";
            foreach ($arr as $a){
                $tem  .= $a['name'].",";
            }
            $tem = substr($tem,0,$tem.length-1);
            $temp['formatname'] = $tem;
        }
        $this->assign("data", $data);
        $this->assign("page",$show);
        $this->display();
    }
    
    public function addimage(){
        $this->display();
    }
    public function addimage_ok(){
        $res = upload('photo');
        dump($res);
    }

    public function add()
    {
        //分配所有楼层
        $floors = $this->floor_model->select();
        $this->assign("floors",$floors);
       /*  分配所属业态 */
        $formats = $this->format_model->select();
        $this->assign("formats",$formats);
        $this->display();
    }
    
    public function add_post()
    {
        if (IS_POST) {
            $res = upload('attac');
            $data = $_POST;
            //判断给铺位号是否存在
            $data['number'] = strtolower(str_replace(array(" ","　","   "),"",$data['number']));
            
            $data['attachmentID'] = $res;
            $res = $this->data_model->where(array("number"=>$data['number']))->count();
            if($res!=0){
                $this->error("<span style='color:#f00'>该铺位号已经存在，请勿重复添加！</span>");
            }
            $data['content'] = str_replace(array("/r/n", "/r", "/n"),"",$data['content']);
            $data['formatID'] = implode(",",$data['formatID']);
			$data['create_time'] = date("Y-m-d H:i:s");
            if ($this->data_model->create() !== false) {
                if ($this->data_model->add($data) !== false) {
                    $this->success("添加成功！", U("Shop/index"));
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error($this->data_model->getError());
            }
        }else{
            $this->error("没有提交内容");
        }
    }

    public function delete()
    {
        if (I('get.id')) {
            $id = I('get.id');
            $res = $this->data_model->delete($id);
            if ($res) {
                $this->success("删除成功！");
            } else {
                $this->error($this->data_model->getLastSql());
            }
        }
        if (I('post.ids')) {
            $ids = I('post.ids');
            $res = $this->data_model->where(array(
                "id" => array(
                    "in",
                    $ids
                )
            ))->delete();
            if ($res) {
                $this->success("批量删除成功！");
            } else {
                $this->error("批量删除失败！");
            }
        }
    }

    public function edit()
    {
        //分配所有楼层
        $floors = $this->floor_model->select();
        $this->assign("floors",$floors);
        /*  分配所属业态 */
        $formats = $this->format_model->select();
        $this->assign("formats",$formats);
        
        $sql = "select a.*,b.savename,b.savepath from ".C('DB_PREFIX')."shop a left join ".C('DB_PREFIX')."attachment b on a.attachmentID = b.id where a.id = ".I('get.id')." limit 1";
        $data = $this->data_model->query($sql);
        $this->assign("data", $data[0]);
        $this->display();
    }

    public function edit_post()
    {
        $res = upload('attac');
        
        $data = $_POST;
        if ($res){
            $data['attachmentID'] = $res;
        }
        $data['formatID'] = implode(",",$data['formatID']);
        $data['content'] = str_replace(array("/r/n", "/r", "/n","'"),"",$data['content']);
        $sql = "UPDATE `ds_shop` SET `shopName`='".$data['shopName']."',`attachmentID`='".$data['attachmentID']."',`number`='".$data['number']."',`address`='".$data['address']."',`floorID`='".$data['floorID']."',`formatID`='".$data['formatID']."',`sp`='".$data['sp']."',`qp`='".$data['qp']."',`jp`='".$data['jp']."',`content`='".$data['content']."',`update_time`='".date("Y-m-d H:i:s")."' WHERE `id` = ".$data['id'];
        $res = $this->data_model->execute($sql);
        /* $shopdata = $this->data_model->create($data);
        $res = $this->data_model->save(); */
        if ($res) {
            $this->success("编辑成功！");
        } else {
            $this->error($this->data_model->getError());
        } 
    }
    
    public function makedata(){
        $sql = "select a.*,b.name floorname,c.name formatname,d.savename,d.savepath,d.size from ".C('DB_PREFIX')."shop a left join ".C('DB_PREFIX')."floor b on a.floorID = b.id left join ".C('DB_PREFIX').
        "format c on a.formatID = c.id left join ".C('DB_PREFIX')."attachment d on a.attachmentID = d.id order by a.floorID asc";
        $data = $this->data_model->query($sql);
        $json = json_encode($data);
        
        $myfile = fopen("./data/data.json","w+");
        fwrite($myfile,$json);
        fclose($myfile);
        
        $this->success("json数据生成成功！");
    }
    
    
    public function setcache(){
        $urlfile = fopen("./data/url.appcache","w+");
        fclose($urlfile);
        tree("./themes/daoshi/Public");
       $basedata = file_get_contents("./data/base.appcache");
       $datastr = "CACHE MANIFEST\r\n#".
                   date("Y-m-d H:i:s")."\r\n".$basedata."\r\n";
       $datastr .= file_get_contents("./data/url.appcache");
       //附件表
       $data = M('attachment')->select();
       foreach ($data as $temp){
           $datastr.="/uploads".$temp['savepath']."m_".$temp['savename']."\r\n";
       }
       //幻灯片表
       $slides = M('slide')->field("slide_pic")->select();
       foreach ($slides as $temp){
           $datastr .= "/data/upload/".$temp['slide_pic']."\r\n";
       }
       
       
       
       $datastr .= "\r\nNETWORK:\r\n\r\n"."FALLBACK:\r\n";
       $myfile = fopen("./data/data.appcache","w+");
       fwrite($myfile,$datastr);
       fclose($myfile);
       //echo "appcache生成成功！";
       $this->display();
       //$this->success("appcache生成成功！");
    }
    
    public function  dirtree(){
        tree("./themes/daoshi/Public");
    }
    
    
    
    public function showwebdata(){
      $data = get_sm_webdata();
      foreach ($data as &$temp){
          $temp['content'] = str_replace(array("/r","/n","/r/n","'"),"",strip_tags($temp['content']));
          $temp['shopName'] = $temp['shopname'];
          $floorID = M('floor')->where(array("smid"=>$temp['areaid']))->getField('id');
          $temp['floorID'] = $floorID?$floorID:0;
          $temp['formatID'] = 0;
          //$res = M('shop')->add($temp);
         
      }
      dump($data);
    }
}